import {
	ref,
	reactive,
	computed,
	nextTick,
	getCurrentInstance,
	onMounted,
	watch
} from 'vue'
import {
	onLoad,
	onShow,
	onHide,
	onReady,
	onUnload,
	onShareAppMessage,
	onPageScroll,
	onReachBottom
} from '@dcloudio/uni-app'
import {
	post,
	uploadFile
} from './api.js'
import {
	Decimal
} from 'decimal.js';

export default {
	ref,
	reactive,
	computed,
	onLoad,
	onHide,
	onShow,
	onReady,
	onUnload,
	post,
	uploadFile,
	nextTick,
	getCurrentInstance,
	onMounted,
	watch,
	onPageScroll,
	onReachBottom,
	onShareAppMessage,
	mem: {},
	vue() {
		return getCurrentInstance().proxy
	},
	//分享

	async $share(title, desc, imgUrl) {
		// #ifdef WEB
		let config = await $post('base/order/get_config', {
			url: location.href,
		}, d => {
			uni.hideLoading()
			return d
		})

		weixinOBJ.config({
			debug: false,
			appId: config.appId,
			timestamp: config.timestamp,
			nonceStr: config.nonceStr,
			signature: config.signature,
			jsApiList: ['chooseWXPay', 'updateAppMessageShareData']
		});

		weixinOBJ.ready(function() {
			weixinOBJ.updateAppMessageShareData({
				title, // 分享标题
				desc, //分享描述
				link: location.href, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
				imgUrl, // 分享图标
				success: function() {
					// 分享成功后的回调
					console.log('分享成功')
					uni.showToast({
						title: '分享成功',
						icon: 'success',
						mask: true
					})
				},
			});
		})
		// #endif

	},
	async $pay(trade_no, type) {
		uni.showLoading({
			title: '加载中',
			mask: true
		})

		let payconfig = await $post('/stores/order_pay', {
			oid: trade_no,
			type: type,
			// #ifdef WEB
			url: location.href,
			// #endif
		}, d => {
			uni.hideLoading()
			return d
		})

		//发起支付
		return await new Promise(ok => {
			// #ifdef MP-WEIXIN
			uni.requestPayment({
				provider: 'wxpay',
				timeStamp: payconfig.timeStamp,
				nonceStr: payconfig.nonceStr,
				package: payconfig.package,
				signType: payconfig.signType,
				paySign: payconfig.paySign,
				success: function(res) {
					ok('success')
				},
				fail: function(err) {
					ok('fail')
				}
			})
			// #endif

			// #ifdef WEB
			weixinOBJ.config({
				debug: false,
				appId: payconfig.config.appId,
				timestamp: payconfig.config.timestamp,
				nonceStr: payconfig.config.nonceStr,
				signature: payconfig.config.signature,
				jsApiList: ['chooseWXPay', 'updateAppMessageShareData']
			});

			weixinOBJ.ready(function() {

				weixinOBJ.chooseWXPay({
					timestamp: payconfig.pay.timeStamp,
					nonceStr: payconfig.pay.nonceStr,
					package: payconfig.pay.package,
					signType: payconfig.pay.signType,
					paySign: payconfig.pay.paySign,
					success: function(res) {
						ok('success')
					},
					fail: function(err) {
						ok('fail')
					}
				});
			})
			// #endif
		})
	},
	jia(a, b) {
		return new Decimal(Number(a)).add(new Decimal(Number(b))).toNumber()
	},
	jian(a, b) {
		return new Decimal(Number(a)).sub(new Decimal(Number(b))).toNumber()
	},
	chen(a, b) {
		return new Decimal(Number(a)).mul(new Decimal(Number(b))).toNumber()
	},
	chu(a, b) {
		return new Decimal(Number(a)).div(new Decimal(Number(b))).toNumber()
	},
	base64_encode: d => Base64.encode(d),
	base64_decode: d => Base64.decode(d),
	/**
	 * 生成二维码
	 * Vue.qrcode('pages/index/index',0)
	 * Vue.qrcode('pages/index/index',1,ID)
	 */
	async qrcode(page = 'pages/index/index', type = 0) {

		let data = [...arguments]
		data.splice(0, 2)
		data.unshift(type)

		let user = xaoi.store('user')
		if (user) data.push(user.id)

		return await $post('account/qrcode', {
			page,
			scene: data.join('-')
		})
	},
	$push(url, is_user = false) {
		if (is_user) {
			var user = uni.getStorageSync('user');
			if (!user) {
				uni.showModal({
					title: '温馨提示',
					content: '请先登录~',
					confirmText: '去登录',
					cancelText: '继续浏览',
					confirmColor: '#0f956e',
					complete(e) {
						if (e.confirm) {
							uni.navigateTo({
								url: "/pages/login/login"
							});
						}
					}
				})
				return;
			}
		};

		switch (url) {
			case "/pages/index/index":
				uni.switchTab({
					url
				});
				break;
			default:
				uni.navigateTo({
					url
				});
				break;
		}
	},
	set(target, source) {
		// 删除 target 中所有不在 source 中的属性
		Object.keys(target).forEach(key => {
			if (!(key in source)) {
				delete target[key];
			}
		});

		// 复制 source 中的属性到 target
		Object.keys(source).forEach(key => {
			target[key] = source[key];
		});
	}
};

export function conf(data = {}) {
	let conf = reactive({
		...data,
		query: {}
	})

	onLoad(query => {
		let data = {
			...query
		}
		if (query.scene) {
			let scene = query.scene.split('-')

			switch (scene[0]) {
				case '0':
					var [scene_type, invite_id] = scene

					data['invite_id'] = invite_id
					break;
				case '1':
					var [scene_type, id, invite_id] = scene

					data['id'] = id
					data['invite_id'] = invite_id
					break;
			}

			if (data.invite_id) {
				xaoi.store('invite_id', data.invite_id)
			}
		}
		conf.query = data
	})

	return conf;
}

let Base64 = (() => {

	var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789*/~";

	let r = {}

	r.encode = function(input) {
		if (typeof input !== 'string') {
			throw Error('仅支持字符串类型的编码转换~')
		};
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = utf8Encode(input);
		while (i < input.length) {
			chr1 = input.charCodeAt(i++);
			chr2 = input.charCodeAt(i++);
			chr3 = input.charCodeAt(i++);
			enc1 = chr1 >> 2;
			enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
			enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
			enc4 = chr3 & 63;
			if (isNaN(chr2)) {
				enc3 = enc4 = 64;
			} else if (isNaN(chr3)) {
				enc4 = 64;
			}
			output = output +
				_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
				_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
		}
		return output;
	};

	r.decode = function(input) {
		var output = "";
		var chr1, chr2, chr3;
		var enc1, enc2, enc3, enc4;
		var i = 0;
		input = input.replace(/[^A-Za-z0-9\*\/\~]/g, "");
		while (i < input.length) {
			enc1 = _keyStr.indexOf(input.charAt(i++));
			enc2 = _keyStr.indexOf(input.charAt(i++));
			enc3 = _keyStr.indexOf(input.charAt(i++));
			enc4 = _keyStr.indexOf(input.charAt(i++));
			chr1 = (enc1 << 2) | (enc2 >> 4);
			chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
			chr3 = ((enc3 & 3) << 6) | enc4;
			output = output + String.fromCharCode(chr1);
			if (enc3 !== 64) {
				output = output + String.fromCharCode(chr2);
			}
			if (enc4 !== 64) {
				output = output + String.fromCharCode(chr3);
			}
		}
		output = utf8Decode(output);
		return output;
	};

	let utf8Encode = function(string) {
		string = string.replace(/\r\n/g, "\n");
		var utfText = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utfText += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utfText += String.fromCharCode((c >> 6) | 192);
				utfText += String.fromCharCode((c & 63) | 128);
			} else {
				utfText += String.fromCharCode((c >> 12) | 224);
				utfText += String.fromCharCode(((c >> 6) & 63) | 128);
				utfText += String.fromCharCode((c & 63) | 128);
			}
		}
		return utfText;
	};

	let utf8Decode = function(utfText) {
		var string = "";
		var i = 0;
		var c = 0;
		var c1 = 0;
		var c2 = 0;
		while (i < utfText.length) {
			c = utfText.charCodeAt(i);
			if (c < 128) {
				string += String.fromCharCode(c);
				i++;
			} else if ((c > 191) && (c < 224)) {
				c1 = utfText.charCodeAt(i + 1);
				string += String.fromCharCode(((c & 31) << 6) | (c1 & 63));
				i += 2;
			} else {
				c1 = utfText.charCodeAt(i + 1);
				c2 = utfText.charCodeAt(i + 2);
				string += String.fromCharCode(((c & 15) << 12) | ((c1 & 63) << 6) | (c2 & 63));
				i += 3;
			}
		}
		return string;
	}

	return r;
})()